package com.wk.wechattool.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PointF;
import android.os.IBinder;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wk.wechattool.R;
import com.wk.wechattool.adapter.FunctionAdapter;
import com.wk.wechattool.bean.CmdType;
import com.wk.wechattool.bean.MarginDecoration;
import com.wk.wechattool.bean.MyEvenBusBean;
import com.wk.wechattool.bean.MyFloatViewParama;
import com.wk.wechattool.icallback.OnItemClickCallBack;
import com.wk.wechattool.tool.MyDeviceInforHelper;
import com.wk.wechattool.tool.WkLog;
import com.wk.wechattool.ui.MyRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FloatingService extends Service {
    private WindowManager windowManager;
    private Service serviceSelef ;
    private SparseArray<MyFloatViewParama> flaotViewParams = new SparseArray< >() ;
    private List<View> floatViews = new ArrayList<>() ;
    private Context context  ;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        serviceSelef = this ;
        context = getApplicationContext() ;
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        showFloatingWindow();
        EventBus.getDefault().register(this);
        WkLog.d("悬浮窗服务 onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    private void showFloatingWindow() {
        final List<MyEvenBusBean> datas= Arrays.asList(
                //new MyEvenBusBean(CmdType.GLOBAL_BACK ,"返回") ,
                new MyEvenBusBean(CmdType.WXSPORT ,"运动点赞") ,
                new MyEvenBusBean(CmdType.FRIND_LIKE ,"朋友圈点赞") ,
                //new MyEvenBusBean(CmdType.MOVE_LEFT ,"左滑") ,
                //new MyEvenBusBean(CmdType.MOVE_RIGHT ,"右滑") ,
                //new MyEvenBusBean(CmdType.MOVE_UP ,"上滑") ,
                //new MyEvenBusBean(CmdType.MOVE_DOWN ,"下滑") ,
                //new MyEvenBusBean(CmdType.ADD_VIEW ,"+") ,
                //new MyEvenBusBean(CmdType.REMOVE_VIEW ,"-") ,
                //new MyEvenBusBean(CmdType.CAN_MOVE ,"不穿透") ,
                //new MyEvenBusBean(CmdType.NOTE_MOVE ," 穿透") ,
                //new MyEvenBusBean(CmdType.CLICK_POINT ,"单点") ,
                //new MyEvenBusBean(CmdType.SCREENSHOT ,"截屏") ,
                new MyEvenBusBean(CmdType.STOP_ALL ,"停止") ,
                new MyEvenBusBean( CmdType.EXIT_SERVICE ,"退出")) ;


        View mainView =addViwe(R.layout.float_window , 0 , MyDeviceInforHelper.getWindowHeigh(getApplication())/2,true) ;
        RecyclerView recyclerView = (RecyclerView) mainView;//mainView.findViewById(R.id.functionRecyView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(  context, 1));
        recyclerView.addItemDecoration(new MarginDecoration( context ));
        FunctionAdapter mAdapter = new FunctionAdapter( context ,datas  , new OnItemClickCallBack() {
            @Override
            public void onItemClick(int index) {
                WkLog.d("悬浮窗服务 onItemClick");
                MyEvenBusBean bean =datas.get(index) ;
                dispatchCmd(bean) ;
            }
        });
        recyclerView.setAdapter(mAdapter);

    }

    private void dispatchCmd( MyEvenBusBean bean){
        CmdType type = bean.getCmdType() ;

        if(type== CmdType.ADD_VIEW){
            addViwe(R.layout.action_view , 10 , 0  ,false) ;
        }

        else if(type== CmdType.REMOVE_VIEW){
            removeActionView();
        }

        else if(type== CmdType.CLICK_POINT){
            if(floatViews.size()>1){
                View theView = floatViews.get(1) ;
                int[] location = new int[2];
                theView.getLocationOnScreen(location);
                int x = location[0] +theView.getWidth()/2;
                int y = location[1] + theView.getHeight()/2;
                bean.setPointF(new PointF(x , y));
            }
        }

        else if(type== CmdType.EXIT_SERVICE){
            serviceSelef.stopSelf();
            throw new RuntimeException("stopSelf没法马上停止，所以搞了一个异常强制退出");
        }

        else if(type== CmdType.CAN_MOVE){
            int size = flaotViewParams.size() ;
            if( size>1){
                for(int i=1 ;  i< size ;i++){
                    MyFloatViewParama tempBean = flaotViewParams.get(i) ;
                    tempBean.getLayoutParams().flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |  WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE ;
                    windowManager.updateViewLayout(floatViews.get(i), tempBean.getLayoutParams());
                }
            }
        }

        else if(type== CmdType.NOTE_MOVE){
            int size = flaotViewParams.size() ;
            if( size>1){
                for(int i=1 ;  i<size ;i++){
                    MyFloatViewParama tempBean = flaotViewParams.get(i) ;
                    tempBean.getLayoutParams().flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
                            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE  ;// 禁止触摸事件
                    windowManager.updateViewLayout(floatViews.get(i), tempBean.getLayoutParams());
                }
            }
        }
        EventBus.getDefault().post( bean );
    }

    private View addViwe( int resourceId , int x , int y ,boolean isRecyView){
        View view = LayoutInflater.from(this).inflate(resourceId, null);
        int viewId =  flaotViewParams.size();
        view.setId(viewId);

        floatViews.add(view);
        boolean isSub =false ;
        if(floatViews.size() >=2){
            TextView btn = (TextView) view;
            btn.setText(String.valueOf( floatViews.size()-1));
            isSub =true ;
        }

        MyFloatViewParama myFloatViewParama = new MyFloatViewParama(x ,y,isSub ) ;
        windowManager.addView(view, myFloatViewParama.getLayoutParams());
        flaotViewParams.put(viewId , myFloatViewParama);
        if(isRecyView){
            MyRecyclerView myRecyclerView = (MyRecyclerView) view;
            myRecyclerView.updateConfig(myFloatViewParama ,windowManager);
        }else{
            view.setOnTouchListener( onTouchListener );
        }
        return view ;
    }


    private void removeActionView(){
        int size = floatViews.size() ;
        if(size>1){
            View view= floatViews.get( size-1) ;
            floatViews.remove(view) ;
            windowManager.removeView(view);
            flaotViewParams.delete(size-1);
        }
    }

    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            int viewId = view.getId();
            MyFloatViewParama myFloatViewParama = flaotViewParams.get(viewId) ;
            if(myFloatViewParama==null){
                return false ;
            }

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    myFloatViewParama.setX( (int) event.getRawX() );
                    myFloatViewParama.setY((int) event.getRawY());
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX -  myFloatViewParama.getX();
                    int movedY = nowY -  myFloatViewParama.getY();
                    myFloatViewParama.setX( nowX );
                    myFloatViewParama.setY( nowY );
                    myFloatViewParama.getLayoutParams().x = myFloatViewParama.getLayoutParams().x + movedX;
                    myFloatViewParama.getLayoutParams().y = myFloatViewParama.getLayoutParams().y + movedY;
                    windowManager.updateViewLayout(view, myFloatViewParama.getLayoutParams()); // 更新悬浮窗控件布局
                    break;
                case MotionEvent.ACTION_UP:
                    view.performClick();
                    break;
                default:
                    break;
            }
            return false;
        }
    };

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent(MyEvenBusBean event) {
        //WkLog.d("悬浮窗服务收到指令="+ event.toString() );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        WkLog.d("悬浮窗服务 onDestroy");
        EventBus.getDefault().unregister(this);
    }
}
